
var http = require('http')

var ejs = require('ejs')

var url = require('url')

var mongoClient = require('mongodb').MongoClient /*引入数据库MongoClient*/

var url = 'mongodb://127.0.0.1:27017/test' //链接数据库地址

var app = require('../EJS/Model/router_server')

http.createServer(app).listen(3000)

app.get("/",function (req,res) {

    var msg = '这是数据库的数据啊'

    ejs.renderFile('../EJS/static/index.ejs',{
        'msg': msg
    },function (err,data) {
        if(err) {
            console.log('模板写入失败')
        }else {
            res.send(data)
        }
    })

})

app.get('/add',function (req,res) {
    mongoClient.connect(url,{ useNewUrlParser: true },function (err, client) {
        if(err) {
            console.log("数据库链接失败")
        }else {
            //增加数据
            var db = client.db("test");
            console.log("数据库连接成功",db)
            db.collection('user').insertOne({
                "name":"慌张",
                "age": 23,
                "sex": "男"
            },function (err, data) {
                if(err) {
                    console.log('增加数据失败')
                }else {
                    res.send('追加數據成功')
                    client.close()
                }
            })
        }
    })
})

app.get('/edit',function (req,res) {
    mongoClient.connect(url,{ useNewUrlParser: true },function (err,client) {
        if(err) {
            console.log("数据库链接失败")
        }else {
            //增加数据
            var db = client.db("test");
            console.log("数据库连接成功",db)
            db.collection('user').updateOne({
                "name":"慌张"
            },{$set:{"age":33}},function (err, data) {
                if(err) {
                    console.log('修改数据失败')
                }else {
                    res.send('修改數據成功')
                    client.close()
                }
            })
        }
    })
})

app.get('/delete',function (req, res) {

    //获取指定参数
    var query = url.parse(req.url,true).query
    var name = query.name

    mongoClient.connect(url,{useNewUrlParser: true},function (err, client) {
        if(err) {
            console.log('连接数据库失败')
        }else {
            //获取db
            var db = client.db('test')
            db.collection('user').removeOne({'name':name},function (err, data) {
                if(err) {
                    console.log('删除数据失败')
                }else {
                    res.send('删除數據成功')
                    client.close()
                }
            })
        }
    })
})